package cn.touna.jss.modules.third.tongdun;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class FraudApiInvoker {

    private final static Logger logger = LogManager.getLogger(FraudApiInvoker.class);
    private static HttpsURLConnection conn;

    public static String invoke(Map<String, Object> params, String apiUrl) {
        OutputStream out = null;
        try {
            URL url = new URL(apiUrl);
            // 组织请求参数
            StringBuilder postBody = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() == null) continue;
                postBody.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(),
                        "utf-8")).append("&");
            }
            if (!params.isEmpty()) {
                postBody.deleteCharAt(postBody.length() - 1);
            }
            SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
            conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            // 设置长链接
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Test-Flag", "true");
            // 设置连接超时
            conn.setConnectTimeout(1000);
            // 设置读取超时，建议设置为500ms。若同时调用了信息核验服务，请与客户经理协商确认具体时间
            conn.setReadTimeout(1000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            out = conn.getOutputStream();
            out.write(postBody.toString().getBytes());
            out.flush();
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                logger.warn("[FraudApiInvoker] invoke failed, response status:" + responseCode);
                return null;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
            return result.toString();
        } catch (Exception e) {
            logger.error("[FraudApiInvoker] invoke throw exception, details: " + e);
        } finally {
            if (conn != null) {
                try {
                    if (null != out) {
                        out.close();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        return null;
    }


    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("partner_code", "touna");// 此处值填写您的合作方标识
        params.put("secret_key", "cf8400e8e7d141909302cd0a6a3d457a");// 此处填写对应app密钥
        params.put("event_id", "Loan_web_20170421");// 此处填写策略集上的事件标识
        params.put("token_id", "");//此处填写设备指纹服务的会话标识，和部署设备脚本的token一致
//        params.put("ip_address", "192.168.6.3");
//        params.put("account_login", "15815319024");// 以下填写其他要传的参数，比如系统字段，扩展字段
        String apiUrl = "https://apitest.tongdun.cn/riskService/v1.1";
        String apiResp = new FraudApiInvoker().invoke(params, apiUrl);
        System.out.println(apiResp);
    }

    public static void heartbeat() {
        final FraudApiInvoker invoker = new FraudApiInvoker();
        final Map<String, Object> params = new HashMap<>();
        params.put("partner_code", "touna");
        params.put("secret_key", "heartbeat");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        invoker.invoke(params, "");
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "FraudApiInvoker Heartbeat Thread").start();
    }
}
